# handle_post_tumblr.py - Handle queue requests to post to Tumblr.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import post_data
import traceback
import tumblr
import yaml

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

class TumblrWorker(webapp.RequestHandler):
    def message_body(self, data):
        result = ''
        if data.embed_html:
            result += data.embed_html + '<br />'
        elif data.image_url:
            result += '<img src="' + data.image_url + '" /><br />'
        if data.description:
            if data.source_url:
                result += '<a href="' + data.source_url + '">' + \
                    data.description + '</a><br />'
            else:
                result += data.description + '<br />'
        if data.user_name:
            if data.user_url:
                result += '<a href="' + data.user_url + '">' + \
                    data.user_name + '</a><br />'
            else:
                result += data.user_name + '<br />'
        return result

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        post_json = self.request.get('post-data')
        if(dgr_yaml_path):
            try:
                logging.info('Posting to Tumblr')
                config = yaml.safe_load(file(dgr_yaml_path, 'r'))
                api = tumblr.Api(config['tumblr_blog'], 
                                 config['tumblr_email'],
                                 config['tumblr_password'])
                data = post_data.PostData().from_json(post_json)
                post = api.write_regular(data.title, self.message_body(data))
                logging.info('Published ' + post['url'])
                logging.info('Posted to Tumblr')
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/post-tumblr', TumblrWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
